/**
 * 
 */
package dp.creat.singleton;

/**
 * This is an example of singleton design pattern It is a convention for
 * ensuring that one and only one object is instantiated for a given class and
 * provides a global point to access it
 * 
 * @author sunaina.sharma
 * 
 */
public class Singleton {

	static Singleton singleton;

	// Volatile keyword ensures that this instance will be handled by only one
	// thread when dealing in a singleton environment
	static volatile Singleton uniqueInstance;

	// Eagerly loading. This guarantees that the instance will be created
	// before any thread accesses it and thus making the instance thread safe
	static {
		singleton = new Singleton();
	}

	/**
	 * Private constructor
	 */
	private Singleton() {
		// This is to avoid instantiation of the object
	}

	/**
	 * Method to getInstance of the class
	 * 
	 * @return
	 */
	public synchronized static Singleton getInstance() {

		// This is lazy initialization. In case of multithreading there can be a
		// case that two thread will acquire different instances of the class.
		// In that case make the getInstance method synchronized. But
		// synchronization can be expensive so better use eager loading
		if (singleton == null) {
			singleton = new Singleton();
		}
		return singleton;
	}

	/**
	 * This method is an alternative to reduce the usage of synchronization.
	 * Work with jdk1.4+
	 * 
	 * @return
	 */
	public static Singleton getInstanceAlt() {
		if (uniqueInstance == null) {
			synchronized (Singleton.class) {
				uniqueInstance = new Singleton();
			}
		}
		return uniqueInstance;
	}
}
